# -*- coding: utf-8 -*-

import sys, os
try:
        import pygtk
        pygtk.require("2.0")
except:
        pass
try:
        import gtk
        import gtk.glade
	import gobject
except:
        sys.exit(1)
from simpledcpp.core.base import DCPPPart, DCPPEvent
from simpledcpp.gui.widgets.list import Tree
from simpledcpp.gui.HumanReadableSize import HRS
import threading
from simpledcpp.gui.base import gtk_lock_required

class FindPage(DCPPPart):
	def __init__(self, parent):
		DCPPPart.__init__(self, parent)
		self.__downloaddir = None
		self._tthdict = {}
		self._results = 0
		self.Events.Subscribe("ON_SEARCH_RESULT", self._searchresult)
		self.type = "search"
		self.name = _('Search')
		Box = gtk.VBox()
		hbox = gtk.HBox()
		self.SearchInput = gtk.Entry()
		self.SearchInput.connect("key-press-event", self._onkey)
		self.SearchInput.show()
		SearchButton = gtk.Button('Button', gtk.STOCK_FIND)
		SearchButton.connect('clicked', self._onsearch)
		SearchButton.show()
                self.combotype = gtk.combo_box_new_text()
                for i in [_('All files'), _('Audio'),_('Archives'),_('Documents'),_('Executable'),_('Pictures'),_('Video'),_('Folders'),_('TTH')]:
                        self.combotype.append_text(i)
                self.combotype.set_active(0)
		self.combotype.show()
                self.combo = gtk.combo_box_new_text()
                self.combo.append_text(_("Size: Normal"))
                self.combo.append_text(_("Size: Less"))
                self.combo.append_text(_("Size: More"))
                self.combo.set_active(0)
		self.combo.show()
		self.SizeInput = gtk.SpinButton()
		self.SizeInput.set_range(0, 99999999999)
		self.SizeInput.set_increments(1, 10000)
		self.SizeInput.show()
		hbox.pack_start(self.SearchInput)
		hbox.pack_start(self.combo)
		hbox.pack_start(self.SizeInput)
		hbox.pack_start(self.combotype, False, False)
		hbox.pack_start(SearchButton, False, False)
		hbox.show()
                menu_items = (
		 ( "/_" + _("Load selected"), 'download', self.download, 0, None),
                 ( "/_" + _("Browse files"), "filelist", self.get_filelist, 0, None ),
		 ( "/_" + _("Load selected to"), "downloadto", self.DownloadTo, 0, None),
		 ( "/_" + _("Copy magnet-link to clipboard"), "magnet", self._magnet,0 , None)
                 )
		self._tree = Tree(
			[_('File'), _('User'), _('Size'), _('TTH'), "INVISIBLE"],
			menu_items,
			str, str ,str, str, gobject.TYPE_INT64
		)
		self._tree.setSortable(2)
		self._tree.treestore.set_sort_func(2, self._sort_func, None)
		Box.pack_start(hbox, False, False)
		Box.show()
                sw = gtk.ScrolledWindow()
                sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
		sw.add(self._tree.widget)
		sw.show()
		Box.pack_start(sw)
		self._widget = Box
		self.HRS = HRS()
		self._lastsearch = ""

        def _sort_func(self, treemodel, iter1, iter2, data = None):
                first = self._tree.treestore.get_value(iter1, 4)
                second = self._tree.treestore.get_value(iter2, 4)
                if first > second:
                        return 1
                elif first < second:
                        return -1
                else:
                        return 0


	def _magnet(self, *args, **kwargs):
		if int(self._tree.selected_rows[4]) == -1:
			self.Notify(_("Error"),_("Can't create magnet-link for selected object"))
			return
		gtk.Clipboard().set_text(self._genMagnet(
			self._tree.selected_rows[0],
			self._tree.selected_rows[4],
			self._tree.selected_rows[3]
		))

	def _onkey(self, widget, Event, *args, **kwargs):
                if Event.keyval == 65293 and self.SearchInput.get_text() != "":
			self._onsearch()

	def _onsearch(self, *args, **kwargs):
		self._tthdict = {}
                self._tree.clear()
		self._results = 0
		self.activate()
                if self.combo.get_active() == 0:
                        size = 'F'
                        ismin = 'T'
                        ismax = '0'

                elif self.combo.get_active() == 1:
                        size = 'T'
                        ismin = 'T'
                        ismax = self.SizeInput.get_value_as_int()

                elif self.combo.get_active() == 2:
                        size = 'T'
                        ismin = 'F'
                        ismax = self.SizeInput.get_value_as_int()
                else:
                        size = 'F'
                        ismin = 'T'
                        ismax = '0'

                datatype = self.combotype.get_active() + 1
                terms = self.SearchInput.get_text()
		self._lastsearch = terms.split(' ')
		if datatype == 9:
			self.Event(DCPPEvent("SEARCH_TTH",(terms,)))
		else:
			self.Event(DCPPEvent("ON_SEARCH_REQUEST",(size, ismin, ismax, datatype, terms)))
		self.Event(DCPPEvent("LSB", (_("Search started") + "... [%s]"%terms,)))

	def get_filelist(self, *args, **kwargs):
		try:
			EXPANDED = "EXPANDTTH:%s"%self._tree.selected_rows[3]
		except:
			EXPANDED = None
		self.Event(DCPPEvent("GET_FILELIST", (None, self._tree.selected_rows[1], EXPANDED)))

        def DownloadTo(self, *args, **kwargs):
                self._dialog = gtk.FileChooserDialog(_("Select directory"),
                                        parent = self.parent.window,
                                        action = gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
                                        buttons = (gtk.STOCK_CANCEL,
                                                        gtk.RESPONSE_REJECT,
                                                        gtk.STOCK_OK,
                                                        gtk.RESPONSE_ACCEPT)
                                        )
                self._dialog.set_default_response(gtk.RESPONSE_ACCEPT)
                response = self._dialog.run()
                if response == gtk.RESPONSE_ACCEPT:
                        self.__downloaddir = self._dialog.get_filename()
                        self._dialog.destroy()
	                if int(self._tree.selected_rows[4]) == -1:
				self.Event(DCPPEvent(
					"NEED_TASK",
					('files.xml.bz2',
					'files.xml.bz2.%s'%self._tree.selected_rows[1],
					0,
					self._tree.selected_rows[1],
					"DOWNLOAD_DIR_TO:%s:%s:%s"%(self._tree.selected_rows[0], self.__downloaddir, self._tree.selected_rows[1]))
				))
                	        return
			nicknames = ""
        	        for i in self._tthdict[self._tree.selected_rows[3]][1:]:
                	        if i != "":
					nicknames = nicknames + i + "<{SPLITTER}>"
	                self.Event(DCPPEvent("NEED_TASK",
				(self._tree.selected_rows[3],
				self._tree.selected_rows[0],
				int(self._tree.selected_rows[4]),
				nicknames, "DOWNLOADTO:%s"%self.__downloaddir)))
                        return
                self._dialog.destroy()
		

	def download(self, *args, **kwargs):
		if int(self._tree.selected_rows[4]) == -1:
			self.Event(DCPPEvent("GET_FILELIST_MD", (None, self._tree.selected_rows[1], self._tree.selected_rows[0])))
			return
		nicknames = ""
		for i in self._tthdict[self._tree.selected_rows[3]][1:]:
			if i != "":
				nicknames = nicknames + i + "<{SPLITTER}>"
		self.Event(DCPPEvent("NEED_TASK", (self._tree.selected_rows[3],self._tree.selected_rows[0], int(self._tree.selected_rows[4]), nicknames)))

	@gtk_lock_required
	def _searchresult(self, Event, *args, **kwargs):
		_n, _fn, _fs, _o,_a, _t = Event.userdata
		my_result = 0
		for i in self._lastsearch:
			try:
				_fn.lower().index(i.lower())
				my_result = 1
				break
			except:
				pass
			try:
				if _t == i:
					my_result = 1
					break
			except:
				pass
		if not my_result:
			return
		try:
			if  int(_fs) > -1:
				_fn = _fn.split('\\')[-1]
		except:
			pass
		# Now we have filename, nickname, filesize, TTH
		_fs = int(_fs)
		if _fs > 0:
			_hfs = self.HRS.byteToHuman(_fs)
		else:
			_hfs = "Directory"
		if self._tthdict.has_key(_t):
			self._tree.append((_fn,_n,_hfs,_t,_fs), parent = self._tthdict[_t][0])
			self._tthdict[_t].append(_n)
		else:
			self._tthdict[_t] = [self._tree.append((_fn, _n, _hfs, _t,_fs)),_n]

		self._results = self._results + 1
#		self.activate()

	def Close(self, *args, **kwargs):
		self.Events.Unsubscribe("ON_SEARCH_RESULT", self._searchresult)

	def activate(self, *args, **kwargs):
		if self._results == 0:
			self.Event(DCPPEvent("LSB",("",)))
		else:
			self.Event(DCPPEvent("LSB",(_("Search results") + ": %s"%self._results,)))
